<?php

/**
 * Project: Espolon
 * Licence: BSD License
 * Link: http://espolon.org/
 * Copyright: Nicolas de Bari Embriz Garcia Rojas <nbari at pobox dot com>
 * Author: Nicolas de Bari Embriz Garcia Rojas <nbari at pobox dot com>
 * Version: Beta
 */

if (!defined('SITE_ROOT')) exit('No direct script access allowed');

/**
 * declare the access congtrol objects (roles and perms)
 */
$tpl->assign('config', array(_('cacheflush'),_('backup'),_('languages'), _('database')));
/**
 * based on the options set the active icon
 */
$tpl->assign('active', $options[0]);

/**
 * if no options default to roles
 */
$command = isset($options[0]) ? $options[0] : 'config';

switch ($command){
	case 'cacheflush':
	  $command_tpl = 'cacheflush.tpl';
	  $tpl->assign('option',$command);
	  $exec_cache = realpath(SITE_ROOT.'../exec/adodbcache/');
	  $command = "find $exec_cache -name 'adodb_*.cache' -exec rm -f {} \;";
    exec($command);
    $db->CacheFlush();
	break;
	case 'backup':
	  if ( isset($options[1]) && $options[1] == 'delete' ) {
	    cleardir(realpath(SITE_ROOT.'../backup/'));
	    $command_tpl = 'backup.tpl';
	    $tpl->assign('option',$command);
	    $tpl->assign('backups_deleted', true);
	  } elseif ( isset($options[1]) && $options[1] == 'download' && file_exists(realpath(SITE_ROOT."../backup/".$options[2])) ) {
      $file = realpath(SITE_ROOT."../backup/".$options[2]);
      header("Content-Disposition: attachment; filename=".$options[2]);
      header("Content-Type: application/x-gzip");
      header("Content-Length: ".filesize($file));
      header("Pragma: no-cache");
      header("Expires: 0");
      readfile($file);
	  } else {
	    $command_tpl = 'backup.tpl';
      $tpl->assign('option',$command);
	    if ( isset($options[1]) && $options[1] == 'generate') {
	      $backup_dir = realpath(SITE_ROOT."../backup");
	      if(!is_dir($backup_dir)) {
	        if(!mkdir($backup_dir, 0700)) {
	          die("error creating backup dir $backup_dir");
	        }
	      }
        $backup = "backup_".date("Y-m-d_H_i_s").".sql.gz";
        $command = DB_MYSQLDUMP." --opt --skip-comments --host=localhost -u".DB_USERNAME." --password=".DB_PASSWORD." ".DB_DATABASE." | gzip -9 > ".$backup_dir."/".$backup."";
        $run = system($command);
        $tpl->assign('backup', $backup);
	    }
      $dir = realpath(SITE_ROOT.'../backup/');
      $files = scandir($dir);
      foreach ($files as $data) {
        if (!preg_match('/^\./', $data)) {
          $file = $dir."/".$data;
          $backups[] = array($data, date("F d Y H:i:s", fileatime($file)));
        }
      }
      $tpl->assign('backups', empty($backups) ? 'empty' : $backups);
	  }
	break;
	case 'config':
	  $conf = new Config();
	  /**
	   *  get languages
	   */
	  $dir = SITE_ROOT.'locale';
    $files = scandir($dir);
    $languages[] = 'Browser Language';
    foreach ($files as $lang) {
      if (!preg_match('/^\./', $lang)) {
        $languages[] = RemoveExtension($lang);
      }
    }
    $conf->SetLanguages($languages);
    /**
     * get themes
     */
    $dir = SITE_ROOT.'themes';
    $files = scandir($dir);
    foreach ($files as $data) {
      if (!preg_match('/^\./', $data)) {
        $themes[] = $data;
      }
    }
    $conf->SetThemes(empty($themes) ? array() : $themes);
    /**
     * Start the form object
     */
	  $form = new EditConfig($tpl, $conf);
    if ($form->validate()) {
      $form->freeze();
      $form->process();
      $db->CacheFlush();
    } else {
      $form->displayForm();
    }
	break;
	case 'languages':
    $tpl->assign('option',$command);
    if (isset($options[1])) {
      $lan = $options[1];
      switch ($lan) {
        case 'podb':
          $conf = new Config();
          $command_tpl = 'edit_podb.tpl';
          $tpl->assign('podb', $db->GetAll('SELECT * FROM core_podb'));
          if (isset($options[2]) && is_numeric($options[2])) {
            $tpl->assign('modify', true);
            $conf->setPodb_id($options[2]);
          }
          $form = new Editpodb($tpl, $conf);
          if ($form->validate()) {
            $form->freeze();
            $form->process();
            $db->CacheFlush();
          } else {
            $form->displayForm();
          }
          break;
        case 'mo':
          $txt_po = 'msgid ""'."\n";
          $txt_po .= 'msgstr ""'."\n";
          $txt_po .= '"POT-Creation-Date: '.date('Y-m-d H:i:s').'\n"'."\n";
          $txt_po .= '"MIME-Version: 1.0\n"'."\n";
          $txt_po .= '"Content-Type: text/plain; charset=UTF-8\n"'."\n";
          $txt_po .= '"Content-Transfer-Encoding: 8bit\n"';

          $po_file = SITE_ROOT.'locale/en_US/LC_MESSAGES/messages.po';
          $mo_file = SITE_ROOT.'locale/en_US/LC_MESSAGES/messages.mo';
          $fh = fopen($po_file, 'w') or die("can't open file");
          fwrite($fh, $txt_po);
          foreach($db->GetAll("SELECT * FROM core_podb") as $po) {
            $txt_po = "\n\n".'msgid "'.$po['msgid'].'"'."\n";
            $txt_po .= 'msgstr "'.$po['msgstr'].'"';
            fwrite($fh, $txt_po);
          }
          fclose($fh);

          $msgfmt = "/usr/bin/msgfmt $po_file -o $mo_file";
          exec($msgfmt);

          $command_tpl = 'edit_languages.tpl';
        break;
        default:
          $command_tpl = 'edit_languages.tpl';
          echo $lan;
        break;
      }
    } else {
      $command_tpl = 'languages.tpl';
      /**
       *  get languages
       */
      $dir = SITE_ROOT.'locale/';
      $files = scandir($dir);
      foreach ($files as $lang) {
        if (!preg_match('/^\./', $lang)) {
          $languages[] = RemoveExtension($lang);
        }
      }
      $tpl->assign('languages',$languages);
    }
	break;
	case 'database':
	  if ( isset($options[1]) && $options[1] == 'optimize' ) {
	    foreach ($db->GetCol("SHOW TABLES") as $table) {
	      $rs = $db->GetRow("OPTIMIZE TABLE $table");
	    }
	  }
	  $command_tpl = 'database.tpl';
	  $tpl->assign('option',$command);
	  $sum_rows = 0;
	  $sum_size = 0;
	  $sum_datafree = 0;
	  foreach ($db->GetALL("SHOW TABLE STATUS") as $value) {
	    $tblsize = doubleval($value['Data_length']) + doubleval($value['Index_length']);
	    $sum_size += $tblsize;
	    $status[] = array($value['Name'], $value['Rows'], format_filesize($tblsize), format_filesize($value['Data_free']), $value['Data_free']);
	    $sum_datafree += $value['Data_free'];
	    $sum_rows += $value['Rows'];
	  }
	  $tpl->assign('status', $status);
	  $tpl->assign('sum_name', count($status));
	  $tpl->assign('sum_rows', $sum_rows);
	  $tpl->assign('sum_size', format_filesize($sum_size));
	  $tpl->assign('sum_datafree', format_filesize($sum_datafree));
	break;
}

?>